// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

package task

import (
	"context"
	"fmt"

	operator "github.com/kumose/kmopt/pkg/cluster/operation"
	"github.com/kumose/kmopt/pkg/environment"
	"github.com/kumose/kmopt/pkg/repository"
)

// Downloader is used to download the specific version of a component from
// the repository, there is nothing to do if the specified version exists.
type Downloader struct {
	component string
	os        string
	arch      string
	version   string
}

// NewDownloader create a Downloader instance.
func NewDownloader(component string, os string, arch string, version string) *Downloader {
	return &Downloader{
		component: component,
		os:        os,
		arch:      arch,
		version:   version,
	}
}

// Execute implements the Task interface
func (d *Downloader) Execute(_ context.Context) error {
	// If the version is not specified, the last stable one will be used
	if d.version == "" {
		env := environment.GlobalEnv()
		ver, _, err := env.V1Repository().WithOptions(repository.Options{
			GOOS:   d.os,
			GOARCH: d.arch,
		}).LatestStableVersion(d.component, false)
		if err != nil {
			return err
		}
		d.version = string(ver)
	}
	return operator.Download(d.component, d.os, d.arch, d.version)
}

// Rollback implements the Task interface
func (d *Downloader) Rollback(ctx context.Context) error {
	// We cannot delete the component because of some versions maybe exists before
	return nil
}

// String implements the fmt.Stringer interface
func (d *Downloader) String() string {
	return fmt.Sprintf("Download: component=%s, version=%s, os=%s, arch=%s",
		d.component, d.version, d.os, d.arch)
}
